from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers
from rest_framework.response import Response

from apps.goods.models import SPUSpecification, SPU, SKUImage, SKU


class SPUSpecSerializer(serializers.ModelSerializer):
    spu = serializers.StringRelatedField(read_only=True)
    spu_id = serializers.IntegerField()

    class Meta:
        model = SPUSpecification
        fields = ('id', 'name', 'spu', 'spu_id')


class SPUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SPU
        fields = ('id', 'name')


class ImageSerializer(serializers.ModelSerializer):
    sku = serializers.PrimaryKeyRelatedField(read_only=True)

    class Meta:
        model = SKUImage
        fields = ('id', 'sku', 'image')

    def create(self, validated_data):
        client = Fdfs_client(settings.FASTDFS_PATH)
        request = self.context['request']
        data = request.data.get('image')
        res = client.upload_by_buffer(data.read())

        if res['Status'] != 'Upload successed.':
            return Response(status=403)

        image_url = res['Remote file_id']

        # sku_id = request.data.get('sku')[0]
        img = SKUImage.objects.create(sku_id=request.data['sku'], image=image_url)

        return img

    def update(self, instance, validated_data):
        client = Fdfs_client(settings.FASTDFS_PATH)
        request = self.context['request']
        data = request.data.get('image')
        res = client.upload_by_buffer(data.read())

        if res['Status'] != 'Upload successed.':
            return Response(status=403)

        image_url = res['Remote file_id']

        # sku_id = request.data.get('sku')[0]
        # img = SKUImage.objects.create(sku_id=request.data['sku'], image=image_url)
        instance.image = image_url
        instance.sku_id = request.data['sku']
        instance.save()


        return instance


class SKUSerializer(serializers.ModelSerializer):
    class Meta:
        model = SKU
        fields = ('id', 'name')
